package com.hmall.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.utils.RabbitMqHelper;
import com.hmall.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Slf4j
@Configuration
@ConditionalOnClass(value = {MessageConverter.class, RabbitTemplate.class})
public class MqConfig {

    @Bean
    //@ConditionalOnBean(ObjectMapper.class)
    public MessageConverter messageConverter(ObjectMapper mapper){
        // 1.定义消息转换器
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter(mapper);
        // 2.配置自动创建消息id，用于识别不同消息
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return new AuthMessageConverter(jackson2JsonMessageConverter);
    }

    static class AuthMessageConverter implements MessageConverter {

        private final MessageConverter delegate;
        public AuthMessageConverter(MessageConverter delegate) {
            this.delegate = delegate;
        }
        @Override
        public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
            Map<String, Object> headers = messageProperties.getHeaders();
            Long userId= UserContext.getUser();
            if(userId!=null){
                log.error("消息发送，正在设置用户信息：{}",userId);
                headers.put("user-info",userId);
            }
            return delegate.toMessage(object, messageProperties);
        }

        @Override
        public Object fromMessage(Message message) throws MessageConversionException {
            Map<String, Object> headers = message.getMessageProperties().getHeaders();
            Object userId = headers.get("user-info");
            if(userId!=null){
                log.error("消息接收，正在设置用户信息：{}",userId);
                UserContext.setUser((Long)userId);
            }
            return delegate.fromMessage(message);
        }
    }

    @Bean
    public RabbitMqHelper rabbitMqHelper(RabbitTemplate rabbitTemplate){
        return new RabbitMqHelper(rabbitTemplate);
    }


}